package edu.lhh;

import java.io.IOException;
import java.util.List;

import edu.lhh.dao.newstypedao;
import edu.lhh.model.newstype;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;
@WebServlet(urlPatterns="/newstype")
public class newtypeServlet extends HttpServlet {
private newstypedao dao = new newstypedao();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String view = "news_type";
		String opt = req.getParameter("opt");
		req.setAttribute("opt", opt);
		if ("add".equals(opt)){
		view= "news_type_au";
		}
		else if("del".equals(opt)){
			int index = Integer.parseInt(req.getParameter("index"));
			dao.del(index);
			List<newstype> lst = dao.findall();
			req.setAttribute("types",lst);
			resp.sendRedirect("./newstype");
			return ;
		}
		else if("updata".equals(opt)){
			newstype type = null;
			String ss = req.getParameter("index");
			int index=0;
			if (ss != null && !"".equals(ss)){
				try{
				index = Integer.parseInt(ss);
				type = dao.findbyid(index);
				}catch(Exception ex){}
			}
			//if (type == null)
			//System.out.println("test");
			if(type == null){
					resp.sendRedirect("./newstype");
					return ;
				}
			else{
					req.setAttribute("type", type);
				}
				view = "news_type_au";	
				
		}
		else{
			List<newstype> lst = dao.findall();
			req.setAttribute("types", lst);
		}
		req.getRequestDispatcher(view+".jsp").forward(req, resp);
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf-8");
		String opt = req.getParameter("opt");
		if("add".equals(opt)){
		newstype type = new newstype();
		type.setId(req.getParameter("id"));
		type.setName(req.getParameter("name"));
		type.setSex(req.getParameter("sex"));
		type.setAge(req.getParameter("age"));
		type.setStf("f");
		dao.add(type);
		}
		else if("updata".equals(opt)){
		newstype type = new newstype();
		type.setId(req.getParameter("id"));
		type.setName(req.getParameter("name"));
		type.setSex(req.getParameter("sex"));
		type.setAge(req.getParameter("age"));
		//String in = req.getParameter("index");
		//int index = Integer.parseInt(in);
		type.setIndex(Integer.parseInt(req.getParameter("index").toString()));
		dao.updata(type);
		}
		resp.sendRedirect("./newstype");
	}

}
